package cn.passlink.www.ServerImpl;

import cn.passlink.www.Enity.sysUser;
import cn.passlink.www.Mapper.sysUserDao;
import cn.passlink.www.Security.LoginUser;
import cn.passlink.www.Server.AuthServer;
import cn.passlink.www.Utils.JsonUtils;
import cn.passlink.www.Utils.JwtUtils;
import cn.passlink.www.Utils.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AuthServerImpl implements AuthServer {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Resource
    private sysUserDao sysUserDao;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * loginAuth
     * 登陆验证
     *
     * @param username
     * @param password
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author passlink
     * @create 2023/10/16
     **/

    @Override
    public Map<String, Object> loginAuth(String username, String password) {
//        验证密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            log.error(username + "登陆验证失败！！！");
            return JsonUtils.resultJson(500, "用户名或密码错误!!!");
        }

        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        sysUser user = loginUser.getUser();
        //       生产JWT返回
        String accessToken = JwtUtils.createToken(user);
        log.info(accessToken + "<---JWT！！！");
        //       存储jwt,用于注销
        String redisKey = user.getUser_id();
        redisTemplate.opsForValue().set(redisKey, accessToken, 12, TimeUnit.HOURS);
//        返回
        Map<String, Object> res = new HashMap<>();
        res.put("accessToken", accessToken);
        res.put("tokenType", "Bearer");
        return JsonUtils.dataJson(200, res, "登陆成功");


    }


    @Override
    public Map<String, Object> register(String username, String password, String email) {
        try {
//            检查用户和邮箱是否已经存在
            sysUser user = sysUserDao.findByUsernameOrEmail(username, email);
            if (user != null) {
                log.error(username+"用户已存在");
                return JsonUtils.resultJson(500, "用户已注册，请使用其他名称或邮箱进行注册！！！");
            }
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = formatter.format(date);
//        加密密码
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            sysUser regUser = new sysUser();
            regUser.setPassword(bCryptPasswordEncoder.encode(password));
            regUser.setNickname(username);
            regUser.setEmail(email);
            regUser.setCreate_time(formattedDate);
            regUser.setLock_status("1");
            regUser.setArticles_counts(0);
//            构造ID
            regUser.setUser_id(RandomUtils.generateUniqueId());
            //        存入数据库
            sysUserDao.pullUser(regUser);
        } catch (NoSuchAlgorithmException e) {
            log.error("注册失败",e);
            return JsonUtils.resultJson(500, "注册失败！！！");
        }

        return JsonUtils.resultJson(200, "注册成功，请到登陆页面登陆！！！");
    }

    @Override
    public Map<String, Object> logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        try {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            String userid = loginUser.getUser().getUser_id();
            if (authentication.isAuthenticated()) {
                SecurityContextHolder.clearContext();
            }
            redisTemplate.delete(userid);
            return JsonUtils.resultJson(200, "退出成功！！！");
        } catch (Exception e) {
            log.error("退出操作失败",e);
            return JsonUtils.resultJson(200, "退出成功！！！");
        }

    }

}
